
package cn.edu.scau.cmi.chenzehan.hibernateframe.POJO;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	
	static {
		try {
			sessionFactory = new Configuration().configure("cn/edu/scau/cmi/chenzehan/hibernateframe/hibernate.cfg.xml").buildSessionFactory();
		}catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
		
	}
	//获取SessionFactory实例
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	//获得ThreadLocal 对象管理的Session实例
	public static Session getSession() throws HibernateException{
		Session session = (Session) threadLocal.get();
		if(session == null || !session.isOpen()) {
			if(sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null)? sessionFactory.openSession():null;
			threadLocal.set(session);
		}
		return session;
		
	}
	//关闭Session实例
	public static void closeSession() throws HibernateException{
		Session session = (Session)threadLocal.get();
		threadLocal.set(null);
		if(session != null) {
			session.close();
		}
	}
	private static void rebuildSessionFactory() {

		try {
			 	Configuration configuration = new Configuration().configure("cn/edu/scau/cmi/chenzehan/hibernateframe/hibernate.cfg.xml");
			 sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.out.println("Error Creating SessionFactory");
			e.printStackTrace();
		}
	}
	public static void shutdown() {
		getSessionFactory().close();
	}
	
}
